/*
 * Dictionary.java
 * Created on Sep 1, 2005
 */
package net.amsoft.iservice.ilink.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.log4j.Logger;

/**
 * @author mohit
 */
public class Dictionary {
	private static Logger oLogger = Logger.getLogger(Dictionary.class);

	/**
	 * Fetches the dictionary document from Plus service over http
	 * 
	 * @return XML string of dictionary
	 */
	private static String[] readTags(String sDictionaryUrl) {
		oLogger.info("readTags() : entry with data : Dictionary Url: "
				+ sDictionaryUrl);
		try {
			URL oDictionary = new URL(sDictionaryUrl);
			URLConnection resolutionCon = oDictionary.openConnection();
			// Cast to a HttpURLConnection
			if (resolutionCon instanceof HttpURLConnection) {
				HttpURLConnection httpConnection = (HttpURLConnection)
				 resolutionCon;

				// int iCode = httpConnection.getResponseCode();
				// logger.debug("readTags() response code: " + iCode);
				//
				// if (iCode > 399 && iCode < 500)
				// return null;
			} else {
				oLogger.warn("readTags() : error - not a http request!");
			}

			BufferedReader in = new BufferedReader(new InputStreamReader(
					resolutionCon.getInputStream()));
			ArrayList<String> alDictionary = new ArrayList<String>();
			String sTag;
			while ((sTag = in.readLine()) != null) {
				if (!sTag.startsWith("+"))
					sTag = '+' + sTag;
				alDictionary.add(sTag);
			}
			in.close();
			oLogger.info("readTags() : exit");
			return (String[]) alDictionary.toArray(new String[alDictionary
					.size()]);
		} catch (MalformedURLException e) {
			oLogger.warn("readTags() : MalformedURLException Exception : "
					+ e.getMessage());
		} catch (IOException e1) {
			oLogger.warn("readTags() : IOException Exception : "
					+ e1.getMessage());
		}
		oLogger.info("readTags() : exit, return null");
		return null;
	}

	/**
	 * Returns the dictionary array
	 * 
	 * @return
	 */
	public static String[] getDictionary(int iType) {
		oLogger.info("getDictionary() : entry with data : Type: " + iType);
		String[] asTags = null;
		switch (iType) {
		case 0:
			asTags = readTags(ILinkConstants.DICTIONARY_PERSONAL_URL);
			break;

		case 1:
			asTags = readTags(ILinkConstants.DICTIONARY_BUSINESS_URL);
			break;
		case 2:
			asTags = readTags(ILinkConstants.DICTIONARY_COMMUNITY_URL);
			break;

		default:
			break;
		}
		oLogger.info("getDictionary() : exit, return Tags: " + asTags);
		return asTags;
	}
}
